<?php

$record_obj = new record_obj();
$client_obj = new client_obj();
$tariff_obj = new tariff_obj();
$lock_obj = new lock_obj();
$task_obj = new task_obj();
$user_obj = new user_obj();
$record_phorum_obj = new record_phorum_obj();
$notify_obj = new notify_obj();

if (!isset($_REQUEST['tsdr_id']) || !is_numeric($_REQUEST['tsdr_id'])) {
    error_obj::setError(new error_obj("bad request id", __FILE__, 'line 4 -> redirect'), UNEXCEPTED);
    base_obj::redirect(ROOT);
}

if (!empty($_REQUEST['result'])) {
    if ($_REQUEST['result'] == 'added_post')
        error_obj::setGood('The post was added');
    if ($_REQUEST['result'] == 'edited_post')
        error_obj::setGood('The post was edited');
    if ($_REQUEST['result'] == 'edited')
        error_obj::setGood('The record was edited');
}

$recordId = (int) $_REQUEST['tsdr_id'];

if (!$record_obj->visibleRecord($recordId)) {
    error_obj::setError(new error_obj("not visible record", __FILE__, 'line 26 -> redirect'), UNEXCEPTED);
    base_obj::redirect(ROOT . '?input=timesheets');
}

$record_data = $record_obj->getRecordById($recordId);

if (error_obj::isError($record_data))
    error_obj::setError($record_data, UNEXCEPTED);
elseif (empty($record_data))
    error_obj::setError(new error_obj("empty record", __FILE__, 'get task data'), EMPTY_RECORD);
else {

    $record_data['date_formated'] = base_obj::convertDateTo($record_data['date'], 'dd/mm/yyyy H:i:s', 'datetime');
    $record_data['client_info'] = $client_obj->getClient($record_data['client']);
    $record_data['type_info'] = $record_obj->getTypeOfRecordById($record_data['type']);
    $record_data['tariff_info'] = $tariff_obj->getTariffById($record_data['tariff']);
    $record_data['user_info'] = $user_obj->getUserById($record_data['user_id']);
    $record_data['locked'] = 0;
    if ($lock_obj->isRecordLocked($record_data['date_formated'])) {
        $record_data['locked'] = 1;
    }

    $filter = array();
    $filter['record_id'] = $recordId;
    $record_data['phorum'] = $record_phorum_obj->getPostsInPhorum($filter, "'when' ASC");
    foreach ($record_data['phorum'] as $key => $post) {
        $record_data['phorum'][$key]['text'] = htmlspecialchars_decode($record_data['phorum'][$key]['text']);
        $record_data['phorum'][$key]['when'] = base_obj::convertDateTo($post['when'], 'dd/mm/yyyy H:i:s', 'datetime');
        $record_data['phorum'][$key]['user_data'] = $user_obj->getUserById($post['user_id'], array('name', 'surname'));
    }

    if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {

        switch ($_REQUEST['action']) {
            case 'edit_post':
                $phorum = $_REQUEST['phorum'];
                $phorum['text'] = base_obj::my_nl2br($phorum['text']);
                $keys = array('record_phorum_id' => $phorum['record_phorum_id']);
                unset($phorum['record_phorum_id']);
                $res = $record_phorum_obj->editPost($phorum, $keys);
                if (error_obj::isError($res)) {
                    error_obj::setError($res, UNEXCEPTED);
                } else {
                    base_obj::redirect(ROOT . '?input=tsdr_more&tsdr_id=' . $recordId . '&result=edited_post#' . $_REQUEST['phorum']['record_phorum_id']);
                }
                break;
            case 'edit_record':
                $recordId = (int) $_REQUEST['recordId'];
                $record_taskId = (int) $_REQUEST['record_taskId'];
                if (empty($recordId))
                    break;
                $originalRecord = $record_obj->getRecordById($recordId);
                $in_data = $_REQUEST['record'];
                $in_data['unit_price'] = $in_data['price'];
                unset($in_data['price']);
                $in_data['date'] = base_obj::convertDateTo($in_data['date']);
                if (!isset($in_data['after_hours']))
                    $in_data['after_hours'] = 0;
                $result = $record_obj->editRecord($in_data, $recordId);
                if (error_obj::isError($result)) {
                    error_obj::setError($result, UNEXCEPTED);
                } else {
                    $change_obj = new change_obj();
                    $change_obj->add_change_with_records_compare($recordId, $originalRecord);
                    $task_obj->updateTaskRate($record_taskId);
                    base_obj::redirect(ROOT . '?input=tsdr_more&tsdr_id=' . $recordId . '&result=edited');
                }
                break;
        }

        $actions = explode("_", $_REQUEST['action']);
        if (in_array('saveMore', $actions)) {
            $redirect_to = '';
            if (!empty($_REQUEST['record_data'])){

                $save_data = $_REQUEST['record_data'];
                $originalRecord = $record_obj->getRecordById($recordId);
                $res = $record_obj->editRecord($save_data, $recordId);
                if (error_obj::isError($res)) {
                    error_obj::setError($res, UNEXCEPTED);
                } else {
                    $change_obj = new change_obj();
                    $change_obj->add_change_with_records_compare($recordId, $originalRecord);
                    $redirect_to = ROOT . '?input=tsdr_more&tsdr_id=' . $recordId . '&result=edited';
                }
                
            }

            if (!empty($_REQUEST['post'])) {
                $record_phorum = array();
                $record_phorum['user_id'] = $_SESSION['user']['user_id'];
                $record_phorum['when'] = date("Y-m-d H:i:s");
                $record_phorum['record_id'] = $recordId;
                $record_phorum['text'] = base_obj::my_nl2br($_REQUEST['post']);

                $res = $record_phorum_obj->addPost($record_phorum);
                if (error_obj::isError($res)) {
                    error_obj::setError($res, UNEXCEPTED);
                } else {

                    if (in_array('send', $actions)) {
                        $db_obj = new db_obj();

                        $sql = "SELECT user_id FROM " . $GLOBALS['tb_record_phorum'] . " WHERE record_id='$recordId' GROUP BY user_id";
                        $subscribers = $db_obj->getCol($sql);

                        if (error_obj::isError($subscribers)) {
                            error_obj::setError($subscribers, UNEXCEPTED);
                        } else {
                            base_obj::debug('subs', $subscribers);
                            $temp = array();
                            foreach ($subscribers as $sub) {
                                $temp[$sub] = $sub;
                            }
                            $subscribers = $temp;
                            if (isset($subscribers[$_SESSION['user']['user_id']]))
                                unset($subscribers[$_SESSION['user']['user_id']]);
                            if (!isset($subscribers[$record_data['user_id']]))
                                $subscribers[$record_data['user_id']] = $record_data['user_id'];
                            if (!empty($record_data['client_info']['contactPerson']) && !isset($subscribers[$record_data['client_info']['contactPerson']]))
                                $subscribers[$record_data['client_info']['contactPerson']] = $record_data['client_info']['contactPerson'];

                            base_obj::debug('subs after', $subscribers);

                            $recipients_emails = array();
                            foreach ($subscribers as $userId) {
                                $email = $user_obj->getUserById($userId, array('email'));
                                if (!error_obj::isError($email))
                                    $recipients_emails[] = $email['email'];
                            }
                            base_obj::debug("recipients", $recipients_emails);

                            $subject = "CM:" . $record_data['client_info']['name'] . ":TSDR problem";
                            $message = '<a href="' . WWW . '?input=tsdr_more&tsdr_id=' . $recordId . '">' . $record_phorum['text'] . '</a>';
                            $message .= '<div>'.$record_data['description'].'</div>';
                            $sender = $user_obj->getUserById($_SESSION['user']['user_id'], array('name', 'surname', 'email'));

                            $send_result = $notify_obj->send($recipients_emails, $message, $subject, array("email" => $sender['email'], "name" => $sender['name'] . " " . $sender['surname']));
                            if (error_obj::isError($send_result))
                                error_obj::setError($send_result, UNEXCEPTED);
                        }
                    }
                    $redirect_to = ROOT . '?input=tsdr_more&tsdr_id=' . $recordId . '&result=added_post';
                }
            }
            if (!empty($redirect_to)){
                base_obj::redirect($redirect_to);
            }
        }
    }

    $GLOBALS['template_data']['record_data'] = $record_data;

    $filter = array(
        'client' => $record_data['client']
    );
    if ($_SESSION['user']['user_type_id'] != USER_TYPE_CLIENT) {
        $order = array(
            'col' => 'added',
            'orderBy' => 'added',
            'order' => 'DESC',
            'table' => '',
            'connector' => ''
        );
        $GLOBALS['template_data']['tasks'] = $task_obj->getListOfTasks($filter, $order);
    }

    if ($_SESSION['user']['user_type_id'] != USER_TYPE_CLIENT) {
        $filter = array();
        $filter['active'] = 0;

        $GLOBALS['template_data']['clients'] = $client_obj->getAllClients('contactPerson, klient_id, name, bad_payer', $filter, 'name ASC');
        $GLOBALS['template_data']['rtypes'] = $record_obj->getRecordTypes();
        $filter = array();
        $filter['type_of_record'] = $record_data['type'];
        $GLOBALS['template_data']['rtariffs_edit'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
        $filter = array(
            'client' => 11,
            'active' => 1
        );
        $GLOBALS['template_data']['rusers'] = $user_obj->getUsers('users_id, name, surname', $filter);
    }
}
?>
